package com.bw.module_main.ui.main

import android.os.Bundle
import android.os.Handler
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.azhon.appupdate.manager.DownloadManager
import com.bawei.lib_common.Router
import com.bw.lib_common.base.BaseActivity
import com.bw.lib_common.base.BaseViewModel
import com.bw.lib_common.livedata_eventbus.Events
import com.bw.lib_common.livedata_eventbus.LiveDataEventBus
import com.bw.lib_common.livedata_eventbuss.LiveEventBus
import com.bw.lib_common.utils.LoggerUtils
import com.bw.module_main.App
import com.bw.module_main.R
import com.bw.module_main.databinding.MainActivityMainBinding
import com.bw.module_main.dialog.AppUpdateDialog
import com.bw.module_main.model.AppUpdateModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * 主页面
 * 1.fragment切换：hide/show
 * 2.判断版本是否需要升级:使用AppUpdate完成下载和安装，注意通知权限手动添加
 * 3.极光推送绑定
 * 4.全局事件总线：
 *  (1)登录成功
 *  (2)退出登录
 *
 *
 */
@AndroidEntryPoint
@Route(path = Router.Ui.MainActivity)
class MainActivity : BaseActivity<BaseViewModel,MainActivityMainBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.main_activity_main
    private val mViewModel:MainViewModel by viewModels()

    private lateinit var mMotoCircleFragment: Fragment
    private lateinit var mMotoClubFragment: Fragment
    private lateinit var mMallFragment: Fragment
    private lateinit var mMineFragment: Fragment
    private lateinit var mMessageFragment: Fragment
    companion object {
        const val TAG = "MainActivity"
        private const val MOTOR_CIRCLE_FRAGMENT = "motor_circle"
        private const val MOTOR_CLUB_FRAGMENT = "club"
        private const val MINE_FRAGMENT = "mine"
        private const val MALL_FRAGMENT = "mall"
        private const val MESSAGE_FRAGMENT = "message"

    }



    override fun initView() {
        super.initView()
        mMotoClubFragment = ARouter.getInstance().build(Router.Ui.ClubFragment).navigation() as Fragment
        mMotoCircleFragment = ARouter.getInstance().build(Router.Ui.MotorCircleFragment).navigation() as Fragment
        mMallFragment = ARouter.getInstance().build(Router.Ui.MallFragment).navigation() as Fragment
        mMessageFragment = ARouter.getInstance().build(Router.Ui.MessageFragment).navigation() as Fragment
        mMineFragment = ARouter.getInstance().build(Router.Ui.MineFragment).navigation() as Fragment
        //默认选中
        navToFragment(R.id.nav_motor_circle)
        mBinding.rgBottom.check(R.id.nav_motor_circle)
    }

    override fun initData() {
        super.initData()
        mViewModel.checkUpdate()

    }
    private  val handler:Handler = Handler()

    override fun initListener() {
        super.initListener()
        handler.postDelayed(Runnable {
            //订阅全局事件：登录成功和退出登录
//            LiveDataEventBus.with(Events.EVENT_LOGIN_SUCCESS,Boolean::class.java).observe(this){
//                if (it){
//                    //登录成功刷新
//                }
//                LoggerUtils.d(TAG,"登录成功"+it)
//            }
//
//            LiveDataEventBus.with(Events.EVENT_LOGOUT,Boolean::class.java).observe(this){
//                if (it){
//                    //退出登录刷新
//                }
//                LoggerUtils.d(TAG,"退出登录"+it)
//            }
            // 观察非粘性事件
            LiveEventBus.with<Boolean>(Events.EVENT_LOGOUT).observe(this) { message ->
                // 处理事件
                LoggerUtils.d(TAG,"退出登录"+message)
            }

        // 观察粘性事件
            LiveEventBus.with<Boolean>(Events.EVENT_LOGIN_SUCCESS, true).observeSticky(this) { message ->
                // 处理事件
                LoggerUtils.d(TAG,"登录成功"+message)
            }
        },10*1000)


        //点击底部导航切换
        mBinding.rgBottom.setOnCheckedChangeListener { group, checkedId ->
            navToFragment(checkedId)
        }
        mViewModel.appUpdateLiveData_.observe(this){updateModel->
            if (updateModel != null){
                if (updateModel.latestVersion.isEmpty()
                    || updateModel.downloadUrl.isNullOrEmpty()
                    || updateModel.latestVersion == "1.0.0" //当前app的版本
                ) {
                    return@observe
                }
            }
            //切割版本号
            val new = updateModel.latestVersion.split(".")
            if (new.isEmpty() || new.size != 3){
                return@observe
            }
            //切割当前版本号
            val current = "1.0.0".split(".")
            //判断是否需要升级
            val needUpdate = isNeedUpdate(new,current)
            if (!needUpdate){
                return@observe
            }
            //弹出版本升级对话框
            AppUpdateDialog(
                    title = String.format("最新版本%s升级说明",updateModel.latestVersion),
                    message = updateModel.message,
//                    force = updateModel.forceUpGrade == 1,
                    force = false,
                    onConfirmClick = {
                      //下载app更新
                        updateApp(updateModel)
                    }
            ).show(supportFragmentManager)

        }


    }
    private fun updateApp(updateModel:AppUpdateModel){
        DownloadManager.Builder(this).run {
            apkUrl(updateModel.downloadUrl)
            apkName(String.format("club%s.apk",updateModel.latestVersion))
            smallIcon(R.mipmap.app_icon)
            showNotification(true)
            showBgdToast(true)
            apkVersionName(updateModel.latestVersion)
            build()
        }.download()

    }

    fun navToFragment(id:Int){
        val bt = supportFragmentManager.beginTransaction()
        //隐藏当前fragment
        hideCurrentFragment(bt)
        //显示目标fragment
        when(id){
            R.id.nav_motor_circle ->{
                //是否添加过，若添加过直接show显示，若没添加过添加进去
                if (supportFragmentManager.findFragmentByTag(MOTOR_CIRCLE_FRAGMENT)?.isAdded == true){
                    bt.show(mMotoCircleFragment)
                }else{
                    bt.add(R.id.fragment_container,mMotoCircleFragment,MOTOR_CIRCLE_FRAGMENT)  //tag不能省略
                }
            }

            R.id.nav_message ->{
                //是否添加过，若添加过直接show显示，若没添加过添加进去
                if (supportFragmentManager.findFragmentByTag(MESSAGE_FRAGMENT)?.isAdded == true){
                    bt.show(mMessageFragment)
                }else{
                    bt.add(R.id.fragment_container,mMessageFragment,MESSAGE_FRAGMENT)  //tag不能省略
                }
            }
            R.id.nav_motor_club -> {
                if (supportFragmentManager.findFragmentByTag(MOTOR_CLUB_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMotoClubFragment, MOTOR_CLUB_FRAGMENT)
                } else {
                    bt.show(mMotoClubFragment)
                }

            }
            R.id.nav_motor_mall -> {
                if (supportFragmentManager.findFragmentByTag(MALL_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMallFragment, MALL_FRAGMENT)
                } else {
                    bt.show(mMallFragment)
                }
            }
            R.id.nav_mine -> {
                if (supportFragmentManager.findFragmentByTag(MINE_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMineFragment, MINE_FRAGMENT)
                } else {
                    bt.show(mMineFragment)
                }

            }
        }
        bt.commit()
    }

    fun hideCurrentFragment(bt:FragmentTransaction){
        if (supportFragmentManager.findFragmentByTag(MESSAGE_FRAGMENT)?.isVisible == true){
            bt.hide(mMessageFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MOTOR_CIRCLE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMotoCircleFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MOTOR_CLUB_FRAGMENT)?.isVisible == true) {
            bt.hide(mMotoClubFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MALL_FRAGMENT)?.isVisible == true) {
            bt.hide(mMallFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MINE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMineFragment)
        }
    }

    /**
     * 判断是否需要更新
     */
    private fun isNeedUpdate(new: List<String>, current: List<String>): Boolean {
        if (new[0].toInt() > current[0].toInt()) {
            return true
        } else if (new[0].toInt() < current[0].toInt()) {
            return false
        }
        if (new[1].toInt() > current[1].toInt()) {
            return true
        } else if (new[1].toInt() < current[1].toInt()) {
            return false
        }
        if (new[2].toInt() > current[2].toInt()) {
            return true
        } else if (new[2].toInt() < current[2].toInt()) {
            return false
        }
        return false
    }

}